package top.haijunit.mark.common.core.config;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.lang.management.ManagementFactory;
import java.util.Date;
import java.util.Optional;

/**
 * @Author 爱做梦的奋斗青年
 * @Date 2021/10/18 15:41
 * @description
 */
@Slf4j
@Configuration(proxyBeanMethods = false)
public class RunnerConfiguration {

    /** 上下文对象实例 */
    @Resource
    private ApplicationContext ctx;

    @Bean
    public ApplicationRunner applicationRunner() {
        String appJvmName = ManagementFactory.getRuntimeMXBean().getName();
        String path = Optional.ofNullable(ctx.getEnvironment().getProperty("server.servlet.context-path")).orElse("");
        String httpPort = ctx.getEnvironment().getProperty("server.port");
        String httpUrl = "http://" + "127.0.0.1" + ":" + Optional.ofNullable(httpPort).orElse("8080") + path;
        return applicationArguments -> {
            String format = String.format("\n ========== 启动服务 =========="
                            + "\n\t 服务名称:\t%s"
                            + "\n\t 进程ID:\t%s"
                            + "\n\t 启动时间:\t%s"
                            + "\n\t 访问路径:\t%s"
                            + "\n ============================",
                    ctx.getEnvironment().getProperty("spring.application.name"),
                    appJvmName.split("@")[0],
                    DateUtil.format(new Date(ctx.getStartupDate()), DatePattern.NORM_DATETIME_MS_PATTERN),
                    httpUrl
            );
            log.info("\033[1;33m {} \033[0m", format);
        };
    }

    @PreDestroy
    public void destroy() {
        String format = String.format("\n ========== 暂停服务 =========="
                        + "\n\t 服务名称：\t%s"
                        + "\n\t 暂停时间：\t%s"
                        + "\n============================",
                ctx.getEnvironment().getProperty("spring.application.name"), DateUtil.now());
        log.info("\033[1;33m {} \033[0m", format);
    }
}
